<?php


namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Jobs\System\ChatExpandTypeCheckJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxClub;
use App\Models\Circle\WxCircle;
use App\Models\Pets\WxPetsAdoption;
use App\Models\Pets\WxPetsAdoptionApply;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopOrderGoods;
use App\Models\Shop\WxShopService;
use App\Models\Used\WxUsedGood;
use App\Models\User\WxUserContactApply;
use App\Models\User\WxUserStudentCertify;
use App\Models\Voter\WxVoter;
use App\Models\Voter\WxVoterPlayer;
use App\Models\WxAuthentication;
use App\Models\WxChat;
use App\Models\User\WxUser;
use App\Wen\Utils\BureauUtils;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\CommentUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\PetUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChatController extends BaseController
{

    public function massages_process(Request $request) {
        $type = _empty_default_($request->type, '');
        if ($type == 'after_sale_message') {
            return $this->after_sale_message($request);
        }else if($type == 'review_object'){
            return $this->review_object($request);
        }
    }


    private function review_object(Request &$request){
        $chat_id = _empty_default_($request->chat_id, 0);
        if(_empty_($chat_id)){
            return $this->fail(200001);
        }
        $chat = WxChat::find($chat_id);
        if(!$chat){
            return $this->fail(200003);
        }
        // 101: 笔记审核 102：评论审核 103：组局审核 104：选票审核 105：选手审核 106：闲置审核 107：圈子审核 108：学生认证审核 109：身份认证审核 110 俱乐部审核
        if(!in_array($chat->expand_type, [101, 102, 103, 104, 105, 106, 107, 108, 109, 110])){
            return $this->fail(200004);
        }

        global $__MINI_GLOBAL_IS_ADMIN_SUPER__,$__MINI_GLOBAL_CURRENT_USER_ID__;
        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            if($chat->expand_type == 105){
                $voter_id = WxVoterPlayer::where('id', $chat->expand_id)->value('voter_id');
                if(_empty_($voter_id)){
                    return $this->fail(200000);
                }
                if(WxVoter::where('id', $voter_id)->value('user_id') != $__MINI_GLOBAL_CURRENT_USER_ID__){
                    return $this->fail(200000);
                }
            }else{
                return $this->fail(200000);
            }
        }
        $flag = _empty_default_($request->flag, 0);
        if(!in_array($flag, [1, 2])){
            return $this->fail(200004);
        }
        if($chat->expand_type == 101){
            //expand_id
            $the_object = WxPost::where('is_examine', 0)->where('id', $chat->expand_id)->first();
            if($the_object){
                PostUtils::post_pass($the_object, $flag);
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 102){
            $the_object = WxComment::where('comment_state', 0)->where('id', $chat->expand_id)->first();
            if($the_object){
                CommentUtils::comment_pass($the_object, $flag);
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 103){
            $the_object = WxBureau::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                        UserUtils::add_user_experience($the_object->user_id, 17, 20);
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 3;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 104){
            $the_object = WxVoter::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                        UserUtils::add_user_experience($the_object->user_id, 16, 20);
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 0;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 105){
            $the_object = WxVoterPlayer::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                        UserUtils::add_user_experience($the_object->user_id, 19, 20);
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 0;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 106){
            $the_object = WxUsedGood::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                        UserUtils::add_user_experience($the_object->user_id, 106, 30);
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 99;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 107){
            $the_object = WxCircle::where('circle_state', 0)->where('id', $chat->expand_id)->first();
            if($the_object){
                if($flag == 1){
                    CircleUtils::circle_pass($the_object, 1, '');
                }else{
                    CircleUtils::circle_pass($the_object, 2, '');
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 108){
            $the_object = WxUserStudentCertify::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                        UserUtils::add_user_experience($the_object->user_id, 18, 30);
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 0;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 109){
            $the_object = WxAuthentication::where('authentication_state', 0)->where('id', $chat->expand_id)->first();
            if($the_object){
                if($flag == 1){
                    UserUtils::authenticate_pass($the_object, 1, '');
                }else{
                    UserUtils::authenticate_pass($the_object, 2, '');
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }else if($chat->expand_type == 110){
            $the_object = WxClub::find($chat->expand_id);
            if($the_object){
                if($flag == 1){
                    if($the_object->status == 0){
                        $the_object->status = 1;
                        $the_object->save();
                    }
                }else{
                    if($the_object->status == 1){
                        $the_object->status = 0;
                        $the_object->save();
                    }
                }
                return $this->success();
            }else{
                WxChat::where('id', $chat->id)->forceDelete();
                return $this->fail(200003);
            }
        }
    }


    private function after_sale_message(Request &$request){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        $order_id = _empty_default_($request->order_id, 0);
        if(_empty_($order_id)){
            return $this->fail(200001);
        }
        $first_order_good = WxShopOrderGoods::where('order_id', $order_id)->where('state', 0)->first();
        if($first_order_good){
            if($first_order_good->goods_type == 7){
                $bureau_id = $first_order_good->goods_id;
                $bureau = WxBureau::find($bureau_id);
                if(!$bureau){
                    return $this->fail(200003);
                }
                if($bureau->user_id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                    return $this->fail(200004);
                }
                $card_flag = true;
                $reply_flag = true;
                $img_reply_flag = true;
                $last_chat = WxChat::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('object_id', $bureau->user_id)->orderByDesc('id')->first();
                if($last_chat && $last_chat->expand_type == 7 && $last_chat->expand_id == $bureau->id){
                    $card_flag = false;
                }
                DB::beginTransaction();
                try {

                    if($card_flag){
                        WxContRepositories::add($__MINI_GLOBAL_CURRENT_USER_ID__, $bureau->user_id, '', '', '', 0, 0, 0, 0, 0, 0, $bureau->id);
                    }

                    // todo:
                    if($reply_flag){
                        if($bureau->pre_sale_reply){
                            $chatModel = new WxChat();
                            $chatModel->user_id = $bureau->user_id;
                            $chatModel->object_id = $__MINI_GLOBAL_CURRENT_USER_ID__;
                            $chatModel->chat_content = _mini_emoji($bureau->after_sale_reply);
                            $chatModel->chat_image = '';
                            $chatModel->chat_audio_url = '';
                            $chatModel->chat_audio_length = 0;
                            $chatModel->is_read = 0;
                            $chatModel->chat_state = 0;
                            $chatModel->save();
                        }
                    }

                    if($img_reply_flag){
                        if($bureau->after_sale_reply_img){
                            $chatModel = new WxChat();
                            $chatModel->user_id = $bureau->user_id;
                            $chatModel->object_id = $__MINI_GLOBAL_CURRENT_USER_ID__;
                            $chatModel->chat_content = '';
                            $chatModel->chat_image = $bureau->after_sale_reply_img;
                            $chatModel->chat_audio_url = '';
                            $chatModel->chat_audio_length = 0;
                            $chatModel->is_read = 0;
                            $chatModel->chat_state = 0;
                            $chatModel->save();
                        }
                    }

                    DB::commit();
                    return $this->success();
                } catch (\Exception $e) {
                    DB::rollBack();
                    _logger_(__file__, __line__, $e->getMessage());
                    return $this->fail(200002);
                }
            }
        }

    }
    /**
     * 用户发起聊天
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addChat(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        if($uid == $oid){
            return $this->fail(200040);
        }

        _limit_user('chat', $uid, 30);

        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }

        $chat_content = $request->input('chat_content', '');
        $chat_image = $request->input('chat_image', '');
        $chat_audio_url = $request->input('chat_audio_url', '');
        $chat_audio_length = $request->input('chat_audio_length', '');
        $refer_id = $request->input('refer_id', 0);
        $shop_good_id = $request->input('shop_good_id', 0);
        $voter_id = _abs(_empty_default_($request->voter_id, 0));
        $bureau_id = _abs(_empty_default_($request->bureau_id, 0));

        if(_empty_($uid) || _empty_($oid)){
            return $this->fail(200001);
        }

        if(_empty_($shop_good_id)){
            $shop_good_id = 0;
        }else{
            $shop_good_id = _abs($shop_good_id);
        }
        if($shop_good_id > 0){
            // 比较特殊，需要转换身份，由商家发送
            $tmp_ = $oid;
            $oid = $uid;
            $uid = $tmp_;
            $last_chat = WxChat::where('user_id', $uid)->where('object_id', $oid)->orderByDesc('id')->first();
            if($last_chat && $last_chat->expand_type == 4 && $last_chat->expand_id == $shop_good_id){
                return $this->success();
            }
        }

        if(_empty_($refer_id)){
            $refer_id = 0;
        }else{
            $refer_id = _abs($refer_id);
        }

        global $__MINI_GLOBAL_PAYCODE_18__;
        if(!$__MINI_GLOBAL_PAYCODE_18__ && $chat_audio_url){
            return $this->fail(700000);
        }


        if(_empty_($refer_id) && _empty_($shop_good_id) && _empty_($bureau_id) && _empty_($voter_id)){
            if(_empty_($chat_content) && _empty_($chat_image) && (_empty_($chat_audio_url) || _empty_($chat_audio_length))){
                return $this->fail(200001);
            }
        }

        if(!UserUtils::is_user_can_chat($uid)){
            return $this->fail(200000, [], '抱歉，您没有聊天权限');
        }

        $model = WxContRepositories::add($uid, $oid, $chat_content, $chat_image, $chat_audio_url, $chat_audio_length, $refer_id, 0, 0, $shop_good_id, null, $bureau_id, $voter_id);

        if($model){
            $websocket_id = GatewayUtils::uid2client_id($oid);
            if($websocket_id){
                GatewayUtils::success($websocket_id, 5, ['chat_content'=>_mini_emoji($chat_content, true), 'chat_image'=>$chat_image,
                    'from_user'=>UserUtils::get_cached_user($uid) ]);
            }

            $model->type = 'user';
            $imgList = array();
            array_push($imgList, ['img_url' => $model->chat_image]);
            $model->imgList = $imgList;
            $model->user = WxUser::where('id', $model->user_id)->first(FieldUtils::userInfoColums());
            $model->datetime = format_datetime($model->created_at);
            if($model->chat_audio_url && $model->chat_audio_length){
                $model->mode = 'audio';
            }else if($model->chat_image){
                $model->mode = 'img';
            }else if($model->refer_id){
                $model->mode = 'refer';
            }else{
                $model->mode = 'text';
            }

            if(!_empty_($model->chat_audio_length)){
                $min = (int)($model->chat_audio_length / 60);
                if($min < 10){
                    $min = '0'.$min;
                }
                $sec = $model->chat_audio_length % 60;
                if($sec < 10){
                    $sec = '0'.$sec;
                }
                $model->chat_audio_length = $min.':'.$sec;
            }

        }

        UserInputSafeCheckJob::dispatch($uid, _mini_emoji($chat_content, true));

        if($chat_image || $chat_audio_url){
            Utils::image_state_change([$chat_image, $chat_audio_url], 1);
        }

        return $this->success($model);
    }

    /**
     * 查询用户聊天记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserChat(Request $request, $limit = 6)
    {

        $uid = $request->uid;
        $oid = $request->oid;

        if(_empty_($uid) || _empty_($oid)){
            return $this->fail(200001);
        }

        $data = WxChat::where(function ($query) use ($uid, $oid) {
            $query->where('user_id', $uid)
                ->where('object_id', $oid);
        })
            ->orWhere(function ($query) use ($uid, $oid) {
                $query->where('user_id', $oid)
                    ->where('object_id', $uid);
            })
            ->orderByRaw('id DESC')
            ->simplePaginate($limit);

        $data->map(function ($v) use ($uid){
            $v->type = 'user';
            $imgList = array();
            array_push($imgList, ['img_url' => $v->chat_image]);
            $v->imgList = $imgList;
            $v->user = WxUser::where('id', $v->user_id)->first(FieldUtils::userInfoColums());
            $v->datetime = format_datetime($v->created_at);

            if($v->chat_audio_url && $v->chat_audio_length){
                $v->mode = 'audio';
            }else if($v->chat_image){
                $v->mode = 'img';
            }else if($v->refer_id){
                $v->mode = 'refer';
                if($v->expand_type != 1 || $v->expand_id != $v->refer_id){
                    ChatExpandTypeCheckJob::dispatch();
                }
            }else if($v->adoption_apply_id){
                $v->mode = 'adoption_reply';
                if($v->expand_type != 3 || $v->expand_id != $v->adoption_apply_id){
                    ChatExpandTypeCheckJob::dispatch();
                }
            }else if($v->contact_apply_id){
                $v->mode = 'contact_apply';
                if($v->expand_type != 2 || $v->expand_id != $v->contact_apply_id){
                    ChatExpandTypeCheckJob::dispatch();
                }
            }else{
                if($v->expand_type > 0){
                    if($v->expand_type == 1){
                        $v->mode = 'refer';
                        $v->refer_id = $v->expand_id;
                    }else if($v->expand_type == 2){
                        $v->mode = 'contact_apply';
                        $v->contact_apply_id = $v->expand_id;
                    }else if($v->expand_type == 3){
                        $v->mode = 'adoption_reply';
                        $v->adoption_apply_id = $v->expand_id;
                    }else if($v->expand_type == 4){
                        $v->mode = 'shop_good';
                        $v->shop_good_id = $v->expand_id;
                    }else if($v->expand_type == 5){
                        $v->mode = 'used_good';
                        $v->used_good_id = $v->expand_id;
                    }else if($v->expand_type == 7){
                        $v->mode = 'bureau';
                        $v->bureau_id = $v->expand_id;
                    }else if($v->expand_type == 8){
                        $v->mode = 'voter';
                        $v->voter_id = $v->expand_id;
                    }else if(in_array($v->expand_type, [101, 102, 103, 104, 105, 106, 107, 108, 109, 110])){
                        $v->mode = 'review';
                    }else{
                        // 101: 笔记审核 102：评论审核 103：组局审核 104：选票审核 105：选手审核 106：闲置审核
                        return $this->fail(200006, [], '数据库expand_type不合法');
                    }
                }else{
                    $v->mode = 'text';
                }
            }


            if($v->mode == 'review'){
                if($v->expand_type == 101){
                    $the_post = WxPost::find($v->expand_id);
                    if($the_post){
                        $posts_content = $the_post->posts_content;
                        if($posts_content){
                            $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
                            $s_content =trim_all_space(strip_tags(html_entity_decode($s_content)), true);
                        }
                        $v->chat_content = $the_post->posts_title ?: PostUtils::get_the_title($s_content, $the_post->id);
                        PostUtils::mediaProcess($the_post, $uid, 90003, 0, true);
                        $v->chat_image = Utils::imgWithStyle($the_post->img, 0, false, true);

                        $v->review = [
                            'target_type' => 1,
                            'target_id' => $v->expand_id,
                            'state' => $the_post->is_examine,
                            'title_tip' => '笔记',
                            'state_tip' => [0=>'待审核', 1=>'审核通过', 2=>'驳回'][$the_post->is_examine],
                            'can_refuse' => 1,
                            'user' => UserUtils::get_cached_user($the_post->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 102){
                    $the_comment = WxComment::find($v->expand_id);
                    if($the_comment){
                        $v->chat_image = $the_comment->comment_img_url;
                        $v->chat_content = $the_comment->comment_content;

                        $v->review = [
                            'target_type' => 25,
                            'target_id' => '评论不可跳转',
                            'state' => $the_comment->comment_state,
                            'title_tip' => '笔记评论',
                            'state_tip' => [0=>'待审核', 1=>'审核通过', 2=>'驳回'][$the_comment->comment_state],
                            'can_refuse' => 1,
                            'user' => UserUtils::get_cached_user($the_comment->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 103){
                    $the_bureau = WxBureau::find($v->expand_id);
                    if($the_bureau){
                        if($the_bureau->image_urls){
                            $v->chat_image = _array_key($the_bureau->image_urls[0], 'url', '');
                        }
                        $v->chat_content = $the_bureau->title;

                        $v->review = [
                            'target_type' => 34,
                            'target_id' => $v->expand_id,
                            'state' => $the_bureau->status == 3 ? 2 : $the_bureau->status,
                            'title_tip' => '组局活动',
                            'state_tip' => [0=>'待审核', 1=>'审核通过', 2=>'下架', 3=>'管理员下架'][$the_bureau->status],
                            'can_refuse' => 1,
                            'user' => UserUtils::get_cached_user($the_bureau->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 104){
                    $the_voter = WxVoter::find($v->expand_id);
                    if($the_voter){
                        $v->chat_content = $the_voter->title;
                        if($the_voter->banners){
                            $v->chat_image = _array_key($the_voter->banners, 0, '');
                        }

                        $v->review = [
                            'target_type' => 33,
                            'target_id' => $v->expand_id,
                            'state' => $the_voter->status,
                            'title_tip' => '选票',
                            'state_tip' => [0=>'审核中', 1=>'推送中', 2=>'驳回'][$the_voter->status],
                            'can_refuse' => 0,
                            'user' => UserUtils::get_cached_user($the_voter->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 105){
                    $player = WxVoterPlayer::find($v->expand_id);
                    if($player){
                        $v->chat_content = $player->show_name;
                        if($player->img_urls){
                            $v->chat_image = _array_key($player->img_urls, 0, '');
                        }
                        $v->review = [
                            'target_type' => 6,
                            'target_id' => '/pagesV/voter/detail/player?id='.$v->expand_id,
                            'state' => $player->status,
                            'title_tip' => '选票选手',
                            'state_tip' => [0=>'审核中', 1=>'推送中', 2=>'驳回'][$player->status],
                            'can_refuse' => 0,
                            'user' => UserUtils::get_cached_user($player->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 106){
                    $the_used = WxUsedGood::find($v->expand_id);
                    if($the_used){
                        $v->chat_content = $the_used->title;
                        if($the_used->image_urls){
                            $v->chat_image = _array_key($the_used->image_urls[0], 'url', '');
                        }

                        $v->review = [
                            'target_type' => 28,
                            'target_id' => $v->expand_id,
                            'state' => $the_used->status == 99 ? 2 : ($the_used->status === 0 ? 0 : 1),
                            'title_tip' => '闲置商品',
                            'state_tip' => FieldUtils::usedGoodState()[$the_used->status],
                            'can_refuse' => 1,
                            'user' => UserUtils::get_cached_user($the_used->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 107){
                    $the_circle = WxCircle::find($v->expand_id);
                    if($the_circle){
                        $v->chat_content = $the_circle->circle_name;
                        $v->chat_image = $the_circle->head_portrait;

                        $v->review = [
                            'target_type' => 2,
                            'target_id' => $v->expand_id,
                            'state' => $the_circle->circle_state,
                            'title_tip' => '新建圈子',
                            'state_tip' => [0=>'审核中', 1=>'推送中', 2=>'驳回'][$the_circle->circle_state],
                            'can_refuse' => 1,
                            'user' => UserUtils::get_cached_user($the_circle->user_id),
                        ];
                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 108){
                    $student = WxUserStudentCertify::where('user_id', $v->expand_id)->first();
                    if($student){
                        $v->chat_content = $student->school;
                        $v->chat_image = $student->picture;

                        $v->review = [
                            'target_type' => 25,
                            'target_id' => '学生认证暂不可跳转',
                            'state' => $student->status,
                            'title_tip' => '学生认证',
                            'state_tip' => [0=>'待审核', 1=>'已通过', 2=>'驳回'][$student->status],
                            'can_refuse' => 0,
                            'user' => UserUtils::get_cached_user($student->user_id),
                        ];
                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 109){
                    $authentication = WxAuthentication::find($v->expand_id);
                    if($authentication){
                        $v->chat_content = $authentication->name;
                        $v->chat_image = $authentication->identity_picture;

                        $v->review = [
                            'target_type' => 25,
                            'target_id' => '身份认证暂不可跳转',
                            'state' => $authentication->authentication_state,
                            'title_tip' => '身份认证',
                            'state_tip' => [0=>'审核中', 1=>'已通过', 2=>'驳回'][$authentication->authentication_state],
                            'can_refuse' => 0,
                            'user' => UserUtils::get_cached_user($authentication->user_id),
                        ];

                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }else if($v->expand_type == 110){
                    $club = WxClub::where('id', $v->expand_id)->first();
                    if($club){
                        $v->chat_content = _empty_default_($club->name_tmp, $club->name);
                        $v->chat_image = _empty_default_($club->avatar_tmp, $club->avatar);

                        $v->review = [
                            'target_type' => 35,
                            'target_id' => $v->expand_id,
                            'state' => $club->status,
                            'title_tip' => '俱乐部审核',
                            'state_tip' => [0=>'待审核', 1=>'已通过', 2=>'驳回'][$club->status],
                            'can_refuse' => 0,
                            'user' => UserUtils::get_cached_user($club->user_id),
                        ];
                    }else{
                        WxChat::where('id', $v->id)->forceDelete();
                    }
                }

                if(_empty_($v->chat_image)){
                    $v->chat_image = Settings::get('img_default', '').'?imageMogr2/thumbnail/200x200/crop/200x200/gravity/center/format/jpg/interlace/0/quality/100';
                }else{
                    $v->chat_image = $v->chat_image.'?imageMogr2/thumbnail/200x200/crop/200x200/gravity/center/format/jpg/interlace/0/quality/100';
                }
            }

            if(!_empty_($v->chat_audio_length)){
                $min = (int)($v->chat_audio_length / 60);
                if($min < 10){
                    $min = '0'.$min;
                }
                $sec = $v->chat_audio_length % 60;
                if($sec < 10){
                    $sec = '0'.$sec;
                }
                $v->chat_audio_length = $min.':'.$sec;
            }

            if(!_empty_($v->refer_id)){
                if($v->refer_id && $v->refer_id > 0){
                    $refer_post = WxPost::find($v->refer_id);
                    if($refer_post){
                        PostUtils::mediaProcess($refer_post, $uid, 15, 0, true);
                        if($refer_post->posts_content_raw){
                            $refer_post->posts_content_raw = strip_tags($refer_post->posts_content_raw);
                        }
                        $v->refer = $refer_post;
                    }else{
                        WxChat::where('id', $v->id)->delete();
                    }
                }else{
                    $v->refer = null;
                }
            }

            if(!_empty_($v->adoption_apply_id)){
                if($v->adoption_apply_id && $v->adoption_apply_id > 0){
                    $adoption_reply = WxPetsAdoptionApply::find($v->adoption_apply_id);
                    if($adoption_reply){
                        $v->adoption_reply = PetUtils::adoption_apply_process($adoption_reply, $uid);
                        $v->adoption_reply->adoption = PetUtils::adoption_process(WxPetsAdoption::find($adoption_reply->pet_adoption_id));
                    }else{
                        WxChat::where('id', $v->id)->delete();
                    }
                }else{
                    $v->adoption_reply = null;
                }
            }

            if(!_empty_($v->used_good_id)){
                $user_good = WxUsedGood::where('id', $v->used_good_id)->first();
                if($user_good){
                    ShopUtils::used_process($user_good);
                    if($user_good->pic){
                        $user_good->pic = $user_good->pic.'?imageMogr2/quality/100/format/webp/interlace/0/crop/200x200/gravity/center/thumbnail/200x';
                    }

                    $user_good->servicer_word = '亲，想要可以直接拍';
                    $v->used_good = $user_good;
                }else{
                    WxChat::where('id', $v->id)->delete();
                }
            }

            if(!_empty_($v->bureau_id)){
                $bureau = WxBureau::where('id', $v->bureau_id)->first();
                if($bureau){
                    BureauUtils::bureau_process($bureau);
                    if($bureau->pic){
                        $bureau->pic = $bureau->pic.'?imageMogr2/quality/100/format/webp/interlace/0/crop/200x200/gravity/center/thumbnail/200x';
                    }
                    $v->bureau = $bureau;
                }else{
                    WxChat::where('id', $v->id)->delete();
                }
            }

            if(!_empty_($v->voter_id)){
                $voter = WxVoter::where('id', $v->voter_id)->first();
                if($voter){
                    if($voter->banners){
                        $voter->pic = $voter->banners[0];
                    }
                    $v->voter = $voter;
                }else{
                    WxChat::where('id', $v->id)->delete();
                }
            }

            if(!_empty_($v->shop_good_id)){
                $data = WxShopGoods::where('id', $v->shop_good_id)->first()->toArray();
                if($data) {
                    // 服务
                    if (isset($data['service_id'])) {
                        $service_tip = '';
                        $data['service'] = WxShopService::whereIn('id', json_decode($data['service_id'], true))->get(['name', 'intro'])->map(function ($s) use (&$service_tip){
                            if(_empty_($service_tip)){
                                $service_tip .= '"'.$s->name.'"';
                            }else{
                                $service_tip .= '，' . '"'.$s->name.'"';
                            }
                            return $s;
                        });
                        if($service_tip){
                            $service_tip = '亲，我们这款商品的服务为' . $service_tip . '~';
                        }
                        $data['service_tip'] = $service_tip;
                        if($data['pic'] && is_array($data['pic']) && count($data['pic']) > 0){
                            $data['pic'][0] = $data['pic'][0].'?imageMogr2/quality/100/format/webp/interlace/0/crop/200x200/gravity/center/thumbnail/200x';
                        }
                    } else {
                        $data['service'] = null;
                        $data['service_tip'] = '';
                    }
                    $data['user_purchase'] = ShopUtils::user_buy_goods_times($uid, $data['id']);
                    $v->shop_good = $data;
                }
            }

            if(!_empty_($v->contact_apply_id)){
                if($v->contact_apply_id && $v->contact_apply_id > 0){
                    $contact_apply = WxUserContactApply::find($v->contact_apply_id);
                    if($contact_apply){
                        if($contact_apply->user_id == $uid){
                            // 己方发送
                            $title = '申请查看对方的';
                            if($contact_apply->is_phone == 1){
                                $title .= '手机号';
                            }
                            if($contact_apply->is_wechat_account == 1){
                                if($contact_apply->is_phone == 1){
                                    $title .= '、微信号';
                                }else{
                                    $title .= '微信号';
                                }
                            }
                            $contact_apply->title = $title;
                        }else{
                            $title = '我申请查看你的';
                            if($contact_apply->is_phone == 1){
                                $title .= '手机号';
                            }
                            if($contact_apply->is_wechat_account == 1){
                                if($contact_apply->is_phone == 1){
                                    $title .= '、微信号';
                                }else{
                                    $title .= '微信号';
                                }
                            }
                            $contact_apply->title = $title;
                        }

                        $contact_apply->status_tip = '申请中';
                        if($contact_apply->status == 1){
                            $contact_apply->status_tip = '已同意';
                        }else if($contact_apply->status == 2){
                            $contact_apply->status_tip = '已过期';
                        }

                        $v->contact_apply = $contact_apply;
                    }else{
                        $v->contact_apply = null;
                    }
                }else{
                    $v->contact_apply = null;
                }
            }


            $allowable[] = [
                'text' => '复制',
                'type' => 'copy',
                'id' => $v->id,
                'raw' => strip_tags($v->chat_content),
                'icon' => 'mini-icon mini-fuzhi'
            ];
            $v->allowable = $allowable;

            return $v;
        });

        return $this->success($data);
    }

    /**
     * 已读对应用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readUserChat(Request $request)
    {
        $uid = $request->uid;
        $oid = $request->oid;

        if(_empty_($oid)){
            return $this->fail(200001);
        }

        $data = WxChat::where([['user_id','=', $oid],['object_id', '=', $uid]])->update(['is_read' => 1]);

        return $this->success($data);
    }


    /**
     * 用户删除聊天记录
     */
    public function userDelMessage(Request $request)
    {
        $uid = $request->uid;
        $userid = $request->userid;


        $data = WxChat::where(function ($query) use ($uid, $userid) {
            $query->where('user_id', $uid)
                ->where('object_id', $userid);
        })
        ->orWhere(function ($query) use ($uid, $userid) {
            $query->where('user_id', $userid)
                ->where('object_id', $uid);
        })->update(['chat_state' => 1]);

        return $this->success($data);
    }
}
